/**
 * 
 */
package com.hand.cloud.b2b.daos.impl;

import de.hybris.platform.ordersplitting.model.StockLevelModel;
import de.hybris.platform.ordersplitting.model.VendorModel;
import de.hybris.platform.ordersplitting.model.WarehouseModel;
import de.hybris.platform.servicelayer.model.ModelService;
import de.hybris.platform.servicelayer.search.FlexibleSearchService;
import de.hybris.platform.servicelayer.search.SearchResult;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hand.cloud.b2b.daos.StockLevelDAO;
import com.hand.cloud.b2b.model.EPStockLevelModel;


/**
 * @author StephenWang
 * @time Aug 15, 2014 10:30:34 AM
 * 
 */
@Component(value = "stockLevelDAO")
public class DefaultStockLevelDAO implements StockLevelDAO
{

	@Autowired
	private ModelService modelService;

	@Autowired
	private FlexibleSearchService flexibleSearchService;

	/**
	 * 创建库存信息
	 * 
	 * @return
	 */
	@SuppressWarnings("deprecation")
	@Override
	public StockLevelModel createStockLevel(EPStockLevelModel stocklevel)
	{
		StockLevelModel stockLevel = modelService.create(StockLevelModel.class);
		WarehouseModel vmodel = new WarehouseModel("20000", new VendorModel("4000"));
		stockLevel.setWarehouse(vmodel);
		stockLevel.setAvailable(stocklevel.getAvailable().intValue());
		stockLevel.setMaxPreOrder(stocklevel.getMaxPreOrder().intValue());
		stockLevel.setMaxStockLevelHistoryCount(stocklevel.getMaxStockLevelHistoryCount().intValue());
		stockLevel.setOverSelling(stocklevel.getOverSelling().intValue());
		stockLevel.setPreOrder(stocklevel.getPreOrder().intValue());
		stockLevel.setProductCode(stocklevel.getProductCode());
		stockLevel.setReserved(stocklevel.getReserved().intValue());
		stockLevel.setTreatNegativeAsZero(true);


		this.modelService.save(stockLevel);
		return stockLevel;
	}

	@Override
	public Integer getSumAvailableByBaseStore(String productPK, String baseStorePK)
	{
		final Map<String, Object> params = new HashMap<String, Object>();
		String fsq = "select sum({stock.available}) From {StockLevel as stock} where {stock.warehouse} in({{select {w.pk} FROM {BaseStore2WarehouseRel as s },{Warehouse as w} where {w.pk}={s.target} and {s.source} = ?baseStore and {stock.productCode} = ?productCode}})";
		params.put("baseStore", baseStorePK);
		params.put("productCode", productPK);
		SearchResult<Integer> searchResult = flexibleSearchService.search(fsq, params);
		List<Integer> resultList = searchResult.getResult();
		return (resultList.get(0));
	}

}
